package com.hospital.hospitalserver.service;

import com.hospital.hospitalserver.entity.PharmacistDetail;
import com.hospital.hospitalserver.entity.UserInfo;
import com.hospital.hospitalserver.entity.Vo.Pharmacist;
import com.hospital.hospitalserver.mapper.DepartmentMapper;
import com.hospital.hospitalserver.mapper.PharmacistMapper;
import com.hospital.hospitalserver.mapper.UserMapper;
import com.hospital.hospitalserver.util.EncryptHelper;
import com.hospital.hospitalserver.util.Pager;
import com.hospital.hospitalserver.util.PagerData;
import com.hospital.hospitalserver.util.Response;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 药剂师接口方法实现类
 * */
@Service
@RequiredArgsConstructor
public class PharmacistService {
    private final PharmacistMapper pharmacistMapper;
    private final UserMapper userMapper;
    private final DepartmentMapper departmentMapper;

    /**
     * 添加药剂师
     * */
    @Transactional(rollbackFor = Exception.class)
    public Response addPharmacist(PharmacistDetail pharmacist){
        // 1.判断添加的账户是否存在重复
        UserInfo u = userMapper.findUserByUsername(pharmacist);
        if(u!=null){
            return Response.error("账户名已存在");
        }

        // 2. 设置默认角色（例如护士角色 role_id = 2）
        pharmacist.setRole_id(4); // 根据实际角色ID设置
        pharmacist.setIs_active(1); // 默认激活
        String encryptedPassword = EncryptHelper.SHA(pharmacist.getUserpass());
        pharmacist.setUserpass(encryptedPassword);

        // 3. 添加用户，此时 pharmacist 对象的 user_id 会被自动填充
        Integer addCount = userMapper.addUser(pharmacist);
        if(addCount==0){
            return Response.error("用户添加失败");
        }

        // 4. 此时 pharmacist.getUser_id() 已经包含新生成的 user_id
        pharmacist.setPharmacist_id(pharmacist.getUser_id());

        // 5. 添加药剂师详细信息
        Integer count = pharmacistMapper.addPharmacist(pharmacist);
        if(count>0){
            //添加成功则更新对应科室药剂师总数
            departmentMapper.UpdateAddPharmacistCountByDepartmentId(pharmacist.getDepartment_id());
            return Response.success();
        }else{
            return Response.error("添加药剂师信息失败");
        }
    }

    /**
     * 编辑药剂师
     * */
    @Transactional(rollbackFor = Exception.class)
    public Response editPharmacist(PharmacistDetail pharmacist){
        // 1.取出药剂师数据信息
        Pharmacist pharmacistInfo = pharmacistMapper.findByPharmacistId(pharmacist.getDepartment_id());

        Integer count = pharmacistMapper.editPharmacist(pharmacist);
        if(count>0){
            //编辑成功之后判断是否更换了科室，如果更换科室要同步更新各个科室的药剂师人数
            // 2. 比对科室信息是否有修改
            if(!pharmacist.getDepartment_id().equals(pharmacistInfo.getDepartment_id())){
                //变更科室
                //减少原科室药剂师人数
                departmentMapper.UpdateDeletePharmacistCountByDepartmentId(pharmacistInfo.getDepartment_id());
                //增加新科室药剂师人数
                departmentMapper.UpdateAddPharmacistCountByDepartmentId(pharmacist.getDepartment_id());
            }
            return Response.success();
        }else{
            return Response.error();
        }
    }

    /**
     * 获取药剂师分页数据总数
     * */
    private Integer getPharmacistCountBySearch(Pager pager){
        return pharmacistMapper.getPharmacistCountBySearch(pager);
    }

    /**
     * 计算分页
     * */
    private Integer getPharmacistPageTotalBySearch(Pager pager){
        Integer pharmacistTotalCounts = getPharmacistCountBySearch(pager);
        Integer pageTotal = 1;//设置初始页码为1
        //数据总条数除以pageSize每页显示条数，如取余数求模，如果有余数，页码+1
        //如果可以整除，则页码等于数据总数除以pageSize
        pageTotal = pharmacistTotalCounts/pager.getPageSize();
        if(pharmacistTotalCounts%pager.getPageSize()>0){
            pageTotal += 1;
        }
        return pageTotal;
    }

    /**
     * 获取药剂师分页数据
     * */
    private List<Pharmacist> getPharmacistMapperDataBySearch(Pager pager){
        Integer currentPage = pager.getCurrentPage();
        Integer startIndex = (currentPage - 1)*pager.getPageSize();
        pager.setStartIndex(startIndex);
        return pharmacistMapper.getPharmacistMapperDataBySearch(pager);
    }

    /**
     * 状态药剂师分页数据
     * */
    public Response getPharmacistPagerDataBySearch(Pager pager){
        PagerData pagerData = new PagerData();
        pagerData.setTotal(getPharmacistCountBySearch(pager));
        pagerData.setPageTotal(getPharmacistPageTotalBySearch(pager));
        pagerData.setData(getPharmacistMapperDataBySearch(pager));
        return Response.success(pagerData);
    }

    /**
     * 获取药剂师列表数据用于排班模板
     * */
    public Response getPharmacistList(){
        return Response.success(pharmacistMapper.getPharmacistList());
    }
}
